package com.clipperl.jingfen

import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    lateinit var localBroadcastManager: LocalBroadcastManager
    lateinit var localReceiver: LocalReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initLocalBroadCast()
        notifyAndroid8()

        val intent = Intent(this, LongRunningService::class.java)
        startService(intent)
    }

    private fun initLocalBroadCast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this)
        var intentFilter = IntentFilter()
        intentFilter.addAction("send_msg")
        localReceiver = LocalReceiver()
        localBroadcastManager.registerReceiver(localReceiver, intentFilter)
    }

    private fun notifyAndroid8() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            var channelId = "notify"
            var channelName = "通知消息"
            var importance = NotificationManager.IMPORTANCE_HIGH
            createNotificationChannel(channelId, channelName, importance)
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelId: String, channelName: String, importance: Int) {
        val channel = NotificationChannel(channelId, channelName, importance)
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    /**
     * 返回键直接回到桌面，不退出程序
     */
    override fun onBackPressed() {
        val intent = Intent(Intent.ACTION_MAIN)
//        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addCategory(Intent.CATEGORY_HOME)
        startActivity(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        localBroadcastManager.unregisterReceiver(localReceiver)
    }

    inner class LocalReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == "send_msg") {
                val msg = intent.getStringExtra("msg")
                tv_content.text = msg
            }
        }
    }
}